<template>
  <div class="pages subcardadd">
    <div class="pageLevel">
      <!-- 表单内容 -->
      <div class="from_main">

        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label-width="0px">
            <el-button type="primary" size="small" @click="submitForm('ruleForm')" v-if="!storeyin">保 存</el-button>
            <el-button size="small" @click="resetForm('ruleForm')">取 消</el-button>
          </el-form-item>
          <p class="jichu">次卡详情</p>
          <el-form-item label="次卡名称" prop="ciname" style="margin-top:20px;">
            <el-input :disabled="storeyin" v-model="ruleForm.ciname" clearable placeholder="输入次卡名称" maxlength="30" size="small"></el-input>
            <span>(4~30字)</span>
          </el-form-item>
          <el-form-item label="参与服务" prop="participation">
            <template>
              <el-button :disabled="storeyin" type="primary" size="small" @click="changeservice()">选择服务</el-button>
              <div class="tableMain" style="width:800px">
                <el-table :data="tableDatas" stripe style="width: 100%" class='table-service' border>
                  <el-table-column prop="name" label="服务名称" align="center">
                  </el-table-column>
                  <el-table-column prop="serviceTime" label="时长" align="center">
                  </el-table-column>
                  <el-table-column prop="price" align="center" label="价格">
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-form-item>
          <el-form-item label='单次服务包括的商品' label-width='150px' v-if='serviceWidthGoods.length > 0'>
            <el-table :data="serviceWidthGoods" border style="width: 750px" class='table-service' max-height='250px'>
              <el-table-column label="序号" width="80" type='index' align='center'></el-table-column>
              <el-table-column prop='goodsName' label="商品名称" width='180' align='center'></el-table-column>
              <el-table-column prop="goodsCode" label="商品条码" width="180" align='center'>
              </el-table-column>
              <el-table-column prop="primaryClassify" label="分类" align='center'>
              </el-table-column>
              <el-table-column prop="goodsNum" label="数量" align='center' width='80'>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="次卡次数" prop="limitofuse">
            <el-input :disabled="storeyin" clearable placeholder="如：20" size="small" v-model="ruleForm.limitofuse">
              <template slot="append">次</template>
            </el-input>
          </el-form-item>
          <el-form-item label="次卡会员价" prop="climoney">
            <el-input :disabled="storeyin" v-model="ruleForm.climoney" clearable placeholder="如：99.99" size="small" @keyup.native='replace(ruleForm,"climoney")'>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="次卡原价" prop="originPrice">
            <el-input :disabled="storeyin" clearable placeholder="如：99.99" size="small" v-model="ruleForm.originPrice" @keyup.native='replace(ruleForm,"originPrice")'>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="营业员提成" prop="sales">
            <el-radio-group :disabled="storeyin" v-model="ruleForm.sales" @change="moneychange">
              <el-radio label="0">按百分比</el-radio>
              <el-radio label="1">按固定金额</el-radio>
            </el-radio-group>
            <template>
              <div v-if="isbai">
                <el-form-item label="" prop="salesbai">
                  <el-input :disabled="storeyin" size="small" v-model="ruleForm.salesbai" @keyup.native='replace(ruleForm,"salesbai")'>
                    <template slot="append">%</template>
                  </el-input>
                </el-form-item>
              </div>
              <div v-if="ismoney">
                <el-form-item label="" prop="salesbai1">
                  <el-input :disabled="storeyin" size="small" maxlength="8" v-model="ruleForm.salesbai1">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </div>

            </template>
          </el-form-item> -->
             <el-form-item label="是否提成" prop="serticheng" v-if="!(soUrce !=5&&isShop==0)">
            <el-radio-group v-model="ruleForm.isCommission" :disabled="storeyin">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
            <template>
              <div v-show="ruleForm.isCommission === '1'">
                <el-select v-model="ruleForm.commissionType" size="small" :disabled="storeyin">
                  <el-option label="比例提成" value="0"></el-option>
                  <el-option label="固定提成" value="1"></el-option>
                </el-select>
                <el-input v-model="ruleForm.number" size="small" :disabled="storeyin"></el-input>
                <span v-if="ruleForm.commissionType == 0">%</span>
                <span v-else>元</span>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group :disabled="storeyin" v-model="ruleForm.status">
              <el-radio label="0">上架</el-radio>
              <el-radio label="1">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="有效期" prop="termvalidity" style="margin-top:20px;">
            <el-input :disabled="storeyin" v-model="ruleForm.termvalidity" clearable placeholder="正整数" size="small">
              <template slot="append">个月</template>
            </el-input>
            <span>（正整数）</span>
          </el-form-item>
        </el-form>
      </div>
      <!-- 选择服务弹窗 -->

      <el-dialog title="选择服务" :visible.sync="dialogVisiblew" width="50%" class="   addshopname shopname">
        <i class="el-icon-close icon" @click="serviceicon"></i>
        <div class="prices">
          <div class="tableMain">
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column label="" width="50">
                <template slot-scope="scope">
                  <el-radio :label="scope.$index" v-model="radio" @change.native="handleSelectionChange2(scope.$index,scope.row)"></el-radio>
                </template>
              </el-table-column>
              <el-table-column property="name" align="center" label="服务名称"> </el-table-column>
              <el-table-column property="serviceTime" align="center" label="时长"> </el-table-column>
              <el-table-column property="price" align="center" label="价格"></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer foot">
              <el-button size="small" type="primary" @click="sureservice">确 定</el-button>
              <el-button size="small" @click="cancelservice">取 消</el-button>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>


<script>
import { mapState } from "vuex";
import util from "@/util";
import {
  saveOrUpdatetimesCard,
  serviceList,
  serviceDetail,
  timesCardDetail
} from "@/api";
export default {
  computed: mapState(["merchantId", "isShop", "soUrce"]),

  data() {
    var limitValiditydity = (rules, value, callback) => {
      // if(!value) {
      //   callback(new Error('不能输入空值'))
      // }
      if (value.length > 11) {
        callback(new Error("输入内容过长"));
      } else {
        callback();
      }
    };
    var limitPrice = (rules, value, callback) => {
      var intPart = "";
      var floatPart = "";
      var strValue = value + "";
      if (strValue.indexOf(".") > 0) {
        intPart = strValue.split(".")[0];
        floatPart = strValue.split(".")[1];
      } else {
        intPart = strValue;
      }
      if (intPart.length > 10) {
        callback(new Error("数值过大"));
      } else if (floatPart.length > 2) {
        callback(new Error("最多精确到小数点后两位"));
      } else {
        callback();
      }
    };
    return {
      radio: "",
      tableData: [],
      tableDatas: [],
      serviceWidthGoods: [], //服务需要消耗的商品
      dialogVisiblew: false,
      editorContent: "",
      ruleForm: {
        ciname: "",
        climoney: "",
        limitofuse: "",
        participation: "",
        termvalidity: "",
        sales: "0",
        salesbai: "",
        salesbai1: "",
        status: "0",
        use: "",
        classOne: "",
        classTwo: "",
        classThree: "",
        originPrice: "",
        isCommission: '0', // 是否设置提成
        commissionType: '0', //提成类型
        number: '' //提成金额或者百分比
      },
      rules: {
        ciname: [
          { required: true, message: "请输入次卡名称", trigger: "blur" },
          {
            min: 4,
            max: 30,
            message: "长度在 4 到 30 个字符",
            trigger: "blur"
          },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        classOne: [
          { required: true, message: "请选择所属一级分类", trigger: "change" },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        classTwo: [
          { required: true, message: "请选择所属二级分类", trigger: "change" },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        classThree: [
          { required: true, message: "请选择所属三级分类", trigger: "change" },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        climoney: [
          {
            required: true,
            message: "请输入次卡会员价",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateOperatingArea,
            trigger: "blur"
          },
          {
            validator: util.validatenum1,
            trigger: "blur"
          },
          {
            validator: limitPrice,
            trigger: "blur"
          }
        ],
        originPrice: [
          {
            required: true,
            message: "请输入次卡原价",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateOperatingArea,
            trigger: "blur"
          },
          {
            validator: util.validatenum1,
            trigger: "blur"
          },
          {
            validator: limitPrice,
            trigger: "blur"
          }
        ],
        salesbai: [
          {
            validator: util.checkSpace,
            trigger: "blur"
          },
          {
            validator: util.validatenum,
            trigger: "blur"
          }
        ],
        salesbai1: [
          {
            validator: util.checkSpace,
            trigger: "blur"
          },
          {
            validator: util.validateOperatingArea,
            trigger: "blur"
          }
        ],
        termvalidity: [
          {
            required: true,
            message: "请输入有效期",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateParkingLot,
            trigger: "blur"
          },
          {
            validator: limitValiditydity,
            trigger: "blur"
          }
        ],
        limitofuse: [
          {
            required: true,
            message: "请输入有效次数",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateParkingLot,
            trigger: "blur"
          },
          {
            validator: limitValiditydity,
            trigger: "blur"
          }
        ],
        participation: [
          { required: false, message: "请选择参与服务", trigger: "change" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }]
      },
      isbai: true,
      ismoney: false,
      storeyin: false,
      fuwutiao: {},
      value: "",
      showTab: ""
    };
  },
  mounted() {
    this.showTab = util.getQuery("showTab");
    console.log(this.showTab);
    if (this.showTab == "2") {
      this.storeyin = true;
      this.cidetail();
    }
    if (this.showTab == "3") {
      this.cidetail();
    }
  },
  methods: {
    cidetail() {
      let data = {
        id: util.getQuery("cardId")
      };
      timesCardDetail(data).then(res => {
        if (res.data.id != "") {
          this.ruleForm.ciname = res.data.name;
          this.ruleForm.classOne = res.data.primaryClassification;
          this.ruleForm.classTwo = res.data.secondClassification;
          this.ruleForm.classThree = res.data.threeClassification;
          this.ruleForm.climoney = res.data.price;
          this.ruleForm.termvalidity = res.data.validDay;
          this.ruleForm.limitofuse = res.data.times;
          this.ruleForm.sales = JSON.stringify(res.data.deductType);
          this.ruleForm.originPrice = res.data.originPrice;
          this.ruleForm.fitPerNum = res.data.fitPerNum;
          this.ruleForm.checkboxGroup = res.data.useExcludeDate.split(",");
          this.ruleForm.appointmentMsg = res.data.appointmentMsg;
          this.ruleForm.ruleHint = res.data.ruleHint;
          this.ruleForm.isCommission = res.data.royalty+ ''
          this.ruleForm.commissionType = res.data.deductType + ''
          this.ruleForm.number = res.data.deductAmount
          if (res.data.deductType == 0) {
            this.isbai = true;
            this.ismoney = false;
            this.ruleForm.salesbai = res.data.deductAmount;
          } else if (res.data.deductType == 1) {
            this.isbai = false;
            this.ismoney = true;
            this.ruleForm.salesbai1 = res.data.deductAmount;
          }
          this.serviceid = res.data.servicesId;
          this.serdetail(this.serviceid);
          // var text = JSON.parse(res.data.remark);
          // this.editorContent = text.remarkText;
          // this.editor.txt.html(this.editorContent);
          var a = {
            name: res.data.servicesName,
            serviceTime: res.data.serviceTime,
            price: res.data.servicePrice
          };
          this.tableDatas.push(a);
          this.ruleForm.status = res.data.status.toString();
        }
      });
    },
    //字符串过滤
    replace(obj, key) {
      let that = this;
      let event = event || window.event;
      if (event.keyCode == 13) {
        setTimeout(() => {
          that.validItem(obj, key);
        }, 100);
      } else {
        that.validItem(obj, key);
      }
    },
    validItem(obj, key) {
      let res = "";
      switch (key) {
        case "salesbai":
        case "climoney":
        case "originPrice":
          res = util.replaceNum(obj[key], 10);
          break;
      }
      this.$set(obj, key, res);
    },
    //获取服务详情
    serdetail(id) {
      let data = {
        id: id
      };
      serviceDetail(data).then(res => {
        if (res.data.goodsList) {
          this.serviceWidthGoods = res.data.goodsList;
        } else {
          this.serviceWidthGoods = [];
        }
        this.fuwutiao = res.data;
      });
    },
    // 保存
    getContent() {
      let deductAmount;
      if (this.ruleForm.sales == 0) {
        deductAmount = this.ruleForm.salesbai;
      } else if (this.ruleForm.sales == 1) {
        deductAmount = this.ruleForm.salesbai1;
      }
      let data = {
        companyId: this.merchantId,
        name: this.ruleForm.ciname,
        price: this.ruleForm.climoney,
        validDay: this.ruleForm.termvalidity,
        times: this.ruleForm.limitofuse,
        deductType: this.ruleForm.sales,
        status: this.ruleForm.status,
        serviceId: this.fuwutiao.id,
        originPrice: this.ruleForm.originPrice,
        deductAmount: deductAmount,
        royalty: this.ruleForm.isCommission,
        deductType: this.ruleForm.commissionType,
        deductAmount: this.ruleForm.number
      };
      if (this.showTab == "3") {
        data.id = util.getQuery("cardId");
      }
      if (this.fuwutiao.id != undefined) {
        saveOrUpdatetimesCard(data).then(res => {
          if (res.code == "200") {
            history.back();
          } 
        });
      } else {
        this.$message({
          type: "error",
          message: "请选择参与服务"
        });
      }
    },

    submitForm(formName) {
       if (this.ruleForm.isCommission == '1' && (!this.ruleForm.number || this.ruleForm.number == 0)) {
        this.$message.error('请输入提成值且大于0！')
        return
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (
            parseFloat(this.ruleForm.climoney) >
            parseFloat(this.ruleForm.originPrice)
          ) {
            this.$message.error("会员价格不能大于原价格");
            return;
          }
          this.getContent();
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      history.back();
    },
    // 营业员提成
    moneychange(val) {
      if (val == "0") {
        this.isbai = true;
        this.ismoney = false;
      } else if (val == "1") {
        this.ismoney = true;
        this.isbai = false;
      }
    },
    // 选择服务
    // 服务的列表
    changeservice() {
      this.dialogVisiblew = true;
      let data = {
        companyId: this.merchantId
      };
      serviceList(data).then(res => {
        this.tableData = res.data;
      });
    },
    // 点击×
    serviceicon() {
      this.dialogVisiblew = false;
    },
    // 点击选中
    handleSelectionChange2(index, row) {
      this.fuwutiao = row;
    },
    // 点击确定
    sureservice(id) {
      if (this.fuwutiao.id != id) {
        this.tableDatas = [];
        this.tableDatas.push(this.fuwutiao);
      }
      this.dialogVisiblew = false;
      this.serdetail(this.fuwutiao.id);
    },
    cancelservice() {
      this.dialogVisiblew = false;
    }
  }
};
</script>
<style scoped>
.from_main .el-input {
  width: 350px;
}
.wxclass .el-form-item {
  float: left;
}

.wxclass .el-form-item:nth-child(2) {
  margin-left: 10px;
}

.wxclass .el-form-item:nth-child(3) {
  margin-left: 10px;
}
/*表单的样式*/

.from_main {
  margin-top: 15px;
}

.from_main p {
  width: 100%;
  color: #444;
  font-size: 14px;
  border-bottom: 1px dashed #ccc;
  padding-bottom: 10px;
}

.from_main .el-input {
  width: 350px;
}

.from_main .input {
  width: 200px;
}

.from_main .line {
  margin-left: 35px;
}

.from_main .el-textarea__inner {
  width: 500px;
}

.from_main .fotter_button {
  margin-left: 350px;
}
.foot {
  margin-top: 20px;
  text-align: center;
}
</style>
<style>
#editorElem p {
  border-bottom: none !important;
}
.from_main .wxclass .el-input {
  width: 200px;
}
.shopname .el-radio__label {
  display: none;
}
.subcardadd .el-input-group--prepend .el-input__inner,
.el-input-group__append {
  border: solid 1px #579ff8;
  background-color: #579ff8;
  color: #fff;
}
.table-service th,
.table-service td {
  padding: 6px 0 !important;
}
</style>
